﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Reflection;
using WcMatch.Models;

namespace WcMatch.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class StuResumeController : ControllerBase
    {
        StuResumeContext _resumeContext;
        StudentContext _studentContext;
        public StuResumeController(StuResumeContext context, StudentContext studentContext)
        {
            _resumeContext = context;
            _studentContext = studentContext;
        }

        [HttpPost]
        public async Task< IActionResult> Add(string citizenId, [FromForm] IFormCollection resume)
        {
            if(string.IsNullOrEmpty(citizenId) || resume.Count == 0) 
                return BadRequest(new ActionStatus(-1, "参数异常"));

            StuResume stuResume = new StuResume(citizenId);
            string parseRsu;
            if (ParseResume(ref stuResume, resume, out parseRsu))
            {
                await _resumeContext.Resumes.AddAsync(stuResume);
                int r = await _resumeContext.SaveChangesAsync();
                if (r > 0) 
                    return Ok(new ActionStatus(200, "保存成功", stuResume.ResumeId));
                else
                    return BadRequest(new ActionStatus(-1, "保存失败"));

            }
            else
                return BadRequest(new ActionStatus(-1, parseRsu));
        }

        private bool ParseResume(ref StuResume resume, IFormCollection dict, out string msg)
        {
            try
            {
                PropertyInfo[] pis = resume.GetType().GetProperties();
                foreach (PropertyInfo prop in pis)
                {
                    if (dict.ContainsKey(prop.Name) && dict[prop.Name].Count() != 0)
                    {
                        var value = dict[prop.Name][0];
                        Console.WriteLine(prop.Name);
                        if (prop.PropertyType.FullName.Contains("DateTime"))
                            prop.SetValue(resume, DateTime.Parse(value));
                        else if (prop.PropertyType.FullName.Contains("Int32"))
                            prop.SetValue(resume, int.Parse(value));
                        else if (prop.PropertyType.FullName.Contains("String"))
                            prop.SetValue(resume, value);
                    }
                }
                msg = "解析成功";
            }
            catch(Exception ex)
            {
                msg = ex.Message;
                return false;
            }
            return true;
        }


        [HttpPost]
        public async Task<IActionResult> Delete(string resumeId)
        {
            if (string.IsNullOrEmpty(resumeId))
                return BadRequest(new ActionStatus(-1, "传入数据异常"));

            var resume = _resumeContext.Resumes.Where(s=>s.ResumeId == resumeId).FirstOrDefault();
            if (resume == null)
                return NotFound(new ActionStatus(-1, "履历信息不存在"));
            else
            {
                _resumeContext.Resumes.Remove(resume);
                int line = await _resumeContext.SaveChangesAsync();
                if (line > 0)
                    return Ok(new ActionStatus(200, "操作成功"));
                else
                    return BadRequest(new ActionStatus(-1, "删除失败"));
            }
        }

        [HttpPost]
        public  async Task< IActionResult> Update(string resumeId, [FromForm] IFormCollection resume) 
        {
            if (string.IsNullOrEmpty(resumeId) || resume.Count == 0)            
                return BadRequest(new ActionStatus(-1, "参数异常"));

            var r = _resumeContext.Resumes.Where(s=>s.ResumeId == resumeId).FirstOrDefault();
            string parseInfo;
            if (r == null)
                return NotFound(new ActionStatus(-1, "未找到"));
            else if(ParseResume(ref r, resume, out parseInfo))
            {
                r.UpdateTime = DateTime.Today;
                int line = await _resumeContext.SaveChangesAsync();
                if (line > 0) 
                    return Ok(new ActionStatus(200, "更新成功", r.ResumeId));
                else
                    return BadRequest(new ActionStatus(-1, "更新失败", r.ResumeId));

            }
            else
                return BadRequest(new ActionStatus(-1, parseInfo, r.ResumeId));
        }


        [HttpGet]
        public IActionResult GetAll(string citizenId) 
        {
            if (string.IsNullOrEmpty(citizenId))
                return BadRequest(new ActionStatus(-1,"参数异常"));
             
            var stu = _studentContext. Students.Where(s=>s.CitizenId == citizenId).FirstOrDefault();
            if (stu == null)
                return NotFound(new ActionStatus(-1, "用户不存在"));

            var resumes = _resumeContext.Resumes.Where(s=>s.CitizenId == citizenId).ToList();
            return Ok(new ActionStatus(200, "查询成功", resumes));
        }

        [HttpGet]
        public IActionResult Get(string resumeId)
        {
            if (string.IsNullOrEmpty(resumeId))
                return BadRequest(new ActionStatus(-1, "参数异常"));
            var resumes = _resumeContext.Resumes.Where(s => s.ResumeId == resumeId).FirstOrDefault();
            if (resumes == null)
                return BadRequest(new ActionStatus(-1, "查询失败"));
            return Ok(new ActionStatus(200, "查询成功", resumes));
        }

        [HttpGet]
        public IActionResult AllEmployee(string cid)
        {
            if (string.IsNullOrEmpty(cid)) return BadRequest(new ActionStatus(-1, "参数异常"));
            var list = _resumeContext.Resumes.Where(s => s.CompanyId == cid).ToList().OrderByDescending(s=>s.BeginTime).DistinctBy(s=>s.CitizenId);
            return Ok(new ActionStatus(200, "查询成功", list)) ;
        }
    }
}
